package org.example.Voutils;

public class ThreadCommunicationDemo {
    private final Object lock = new Object();
    private boolean flag = true;
    public void startThreads(){
        Thread numberThread =   new Thread(()->{
            for (int i = 1; i <= 52; i++) {
                synchronized (lock){
                    while (!flag){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(i<10?"0"+i:i);
                    if(i%2==0){
                        flag = false;
                        lock.notify();
                    }
                }
            }
        });
        Thread letterThread = new Thread(() -> {
            char letter = 'A';
            for (int i = 1; i <= 26; i++) {
                synchronized (lock) {
                    while (flag) {
                        try {
                            lock.wait(); // 等待数字线程的通知
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    // 打印字母
                    System.out.print(letter);
                    letter++;
                    flag = true;
                    lock.notify(); // 通知数字线程
                }
            }
        });
        numberThread.start();
        letterThread.start();
        // 等待线程完成
        try {
            numberThread.join();
            letterThread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }


    }
}
